package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"strings"
	"sync"
)

type MDFile struct {
	Path     string     `json:"path"`
	Tags     []string   `json:"tags"`
	WikiLink []WikiLink `json:"wiki_link"`
}

func main() {
	log.Println("LGOU Running")
	text, err := download("https://note.ftls.xyz/help/kkbt-sum.md")
	if err != nil {
		fmt.Println(err)
		return
	}
	err = saveFile("content/kkbt/sum.json", text)
	if err != nil {
		fmt.Println(err)
		return
	}
	var sumNow FileEntries
	err = json.Unmarshal([]byte(text), &sumNow)
	if err != nil {
		fmt.Println(err)
		return
	}
	// read sum.old.json
	sumOld, err := readOldSumJSON("content/kkbt/sum.old.json")
	if err != nil {
		fmt.Println(err)
		return
	}
	// 生成计划列表 多线程
	updated, deleted, added := compareLists(sumOld, sumNow)
	fmt.Println("added:", added)
	fmt.Println("deleted:", deleted)
	fmt.Println("updated:", updated)

	downloadList := []FileEntry{}
	fmt.Println("\n--- Run START ---")
	for _, item := range added {
		fmt.Println("Added " + item.Path)
		downloadList = append(downloadList, item)
	}
	for _, item := range deleted {
		fmt.Println("Deleted " + item.Path)
		err = os.Remove("content/" + item.Path)
		if err != nil {
			fmt.Println(err)
		}
	}
	for _, item := range updated {
		fmt.Println("Updated " + item.Path)
		downloadList = append(downloadList, item)
	}
	// 执行下载
	fmt.Println("--- Download ---")
	var wg sync.WaitGroup
	downloadConcurrently(downloadList, "content/", &wg)
	wg.Wait()
	// err = os.Rename("sum.json", "sum.old.json")
	// if err != nil {
	// 	fmt.Println(err)
	// }
	sumMd := "**目录:**\n{{< tree >}}\n**索引列表:**\n"
	for _, item := range sumNow {
		sumMd += fmt.Sprintf("[[%s]]\n", item.Path[:len(item.Path)-3])
	}
	sumMd += "\n构建于 " + TimeFmt("2006-01-02 15:04:05") + "\n"
	err = saveFile("content/kkbt/sum.md", sumMd)
	if err != nil {
		fmt.Println(err)
	}

	// 生成文件列表树
	root := Node{Path: "/", Type: "dir", Name: "文库"}
	for _, file := range sumNow {
		buildTree(&root, file)
	}

	result, err := json.MarshalIndent(root, "", "  ")
	if err != nil {
		fmt.Println(err)
	}
	err = saveFile("data/tree.json", string(result))
	if err != nil {
		fmt.Println(err)
	}

	// 生成 markdown wiki link map

	// Read markdown files

	filesInfo := []MDFile{}

	//  sum.md _index.md
	// sumNow = append(sumNow, FileEntry{Path: "kkbt/sum.md", Mtime: 0})
	// sumNow = append(sumNow, FileEntry{Path: "kkbt/_index.md", Mtime: 0})
	sumNow = append(FileEntries{FileEntry{Path: "kkbt/_index.md", Mtime: 0}, FileEntry{Path: "kkbt/sum.md", Mtime: 0}}, sumNow...)

	for _, file := range sumNow {
		extracted, err := extractContent("content/" + file.Path)
		if err != nil {
			fmt.Println(err)
		}
		wikiLinks, tags, err := extractWikiLinksAndTags(extracted.MarkdownContent)
		if err != nil {
			fmt.Println(err)
		}
		filesInfo = append(filesInfo, MDFile{Path: file.Path, Tags: tags, WikiLink: wikiLinks})
	}

	mapList := [][]string{}
	for _, it := range filesInfo {
		for _, wikiLink := range it.WikiLink {
			link1 := strings.TrimSuffix(it.Path, ".md")
			link1 = strings.TrimSuffix(link1, "/_index")
			mapList = append(mapList, []string{link1, wikiLink.Link})
		}
	}
	result, err = json.MarshalIndent(mapList, "", "  ")
	if err != nil {
		fmt.Println(err)
	}
	err = saveFile("data/map.json", string(result))
	if err != nil {
		fmt.Println(err)
	}

}
